package com.yc.bank.dao;

import com.yc.bank.bean.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class AccountDao {

    @Resource
    JdbcTemplate jdbc;

    public List<Account> selectAll(){
        String sql = "select * from bank_account";
        // BeanPropertyRowMapper 自动将数据库字段值映射到实体属性中
        //final List<Account> list = jdbc.query(sql, new BeanPropertyRowMapper<Account>());
        final List<Account> list = jdbc.query(sql, new RowMapper<Account>() {
            @Override
            public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
                Account account = new Account();
                account.setId(rs.getString("id"));
                account.setPassword(rs.getString("password"));
                account.setBalance(rs.getDouble("balance"));
                return account;
            }
        });
        return list;
    }

    public List<Account> selectAll1(){
        String sql = "select * from bank_account";
        // BeanPropertyRowMapper 自动将数据库字段值映射到实体属性中
        final List<Account> list = jdbc.query(sql,
                new BeanPropertyRowMapper<Account>(Account.class));
        return list;
    }

    public void updateBalanceById(String aid, double money){
        String sql = "update bank_account" +
                " set balance = balance + ?" +
                " where id = ?";
        jdbc.update(sql, money, aid);
    }



}
